package com.salim.leetcode.$103;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class BinaryTreeZigzagLevelOrderTraversal {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root==null){
            return result;
        }
        Stack<TreeNode> lr = new Stack<>();
        Stack<TreeNode> rl = new Stack<>();
        lr.push(root);
        while (!lr.isEmpty()||!rl.isEmpty()){
            List<Integer> sub = new ArrayList<>();
            if(!lr.isEmpty()){
                while (!lr.isEmpty()){
                    TreeNode node = lr.pop();
                    sub.add(node.val);
                    if(node.left!=null){
                        rl.push(node.left);
                    }
                    if(node.right!=null){
                        rl.push(node.right);
                    }
                }
            }else if(!rl.isEmpty()){
                while (!rl.isEmpty()){
                    TreeNode node = rl.pop();
                    sub.add(node.val);
                    if(node.right!=null){
                        lr.push(node.right);
                    }
                    if(node.left!=null){
                        lr.push(node.left);
                    }

                }
            }
            result.add(sub);
        }
        return result;
    }

    class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
   }
}
